<template>
  <section class="sample-section"  v-loading.lock="loading" element-loading-text="拼命加载中">
    <el-form :model="data" :rules="dataRule" ref="dataForm" label-width="160px" v-if="type === 'import'">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>数据导入</span>
        </div>
        <el-row :gutter="10" class="item-row">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="付款明细模板" prop="username">
              <el-button type="text" @click="downloadfile()">点击下载模板</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="item-row">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="导入付款明细">
              <el-upload class="uploadBtn" ref="upload"
                         :data="{company_id: dataForm.company_id, date: dataForm.date, total_amount: dataForm.total_amount, task_id: dataForm.task_id}"
                         :action="getUrl()"
                         :headers="{ token: $cookie.get('token') }"
                         :on-change="handleFileChange"
                         :on-success="handleUploadSuccess"
                         :on-error="handleUploadError"
                         :file-list="dataForm.fileList"
                         :limit="1"
                         :auto-upload="false">
                <el-button type="primary" size="small">浏览</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="item-row">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="选择导入企业">
              <el-select v-model="dataForm.company_id" filterable @change="companyChange" placeholder="选择导入企业">
                <el-option
                  v-for="item in companys"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="item-row">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="结算周期">
              <el-date-picker v-model="dataForm.date" value-format="yyyyMMdd" type="date" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="item-row">
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="结算金额">
              <el-input v-model="dataForm.total_amount" placeholder="支付金额">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="item-row">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="所属任务">
              <el-select v-model="dataForm.task_id" >
                <el-option
                  v-for="item in tasks"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10" class="item-row">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item>
              <el-button type="warning" @click="dataFormSubmit()" :disabled="submit">提   交</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>使用说明:</span>
        </div>
        <div class="desc">
          <p class="danger-text">1. 请先下载付款明细模板；</p>
          <p class="danger-text">2. 下载的模板中, 表头信息请勿改动;</p>
          <p class="danger-text">3. 上传时请检查,要上传的文件中是否存在科学计数法(如:2.01709E+15),或其他不正常显示的数据,以免造成不必要的损失;</p>
          <p class="danger-text">4. 上传的数据中,请注意金额是否正确</p>
          <p class="danger-text">5. 如果上传的信息中有长数字串,请将 excle 设置成文本格式;</p>
        </div>
      </el-card>

    </el-form>

    <validate :headData="headData" :tableData="tableData" @cancel="handleCancel" v-else></validate>
  </section>
</template>


<script>
  import validate from './validate'
  export default {
    data () {
      return {
        loading: false,
        type: 'import',
        dataForm: {
          company_id: '',
          date: '',
          total_amount: '',
          task_id: '',
          file_name: '',
          fileList: []
        },
        headData: [],
        tableData: [],
        search: {
          title: '',
        },
        pageIndex: 1,
        pageSize: 300,
        totalPage: 0,
        companys: [],
        tasks: []
      }
    },
    components: {
      validate
    },
    mounted () {
    },
    activated () {
      this.loading = false
      this.init();
    },
    methods: {
      init () {
        this.loading = true
        this.$http({
          url: this.$http.adornUrl('/company/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'title': this.search.title
          })
        }).then(({data}) => {
          let _list = data.page.list
          this.companys = _list.map(function(val, idx, _list) {
            return Object.assign({}, {'id': val.company_id, 'title': val.title})
          })
          setTimeout(() => {
            this.loading = false
          }, 500);
        })
      },
      handleCancel() {
        this.type = 'import'
        this.dataForm.fileList = []
        this.$nextTick(() => {
          this.dataForm.fileName = ''
        })
      },
      downloadfile() {
        this.$http({
          url: this.$http.adornUrl('/payment/template'),
          method: 'get',
          responseType: 'blob'
        }).then((res) => {
          let _data = res.data
          let blob = new Blob([_data])
          let reader = new FileReader()
          reader.readAsDataURL(blob)
          reader.onload = (e) => {
            let a = document.createElement('a')
            a.download = '交易导入模板.xlsx'
            a.href = e.target.result
            document.body.appendChild(a)
            a.click()
            a.remove()
          }
        })
      },
      companyChange(company_id) {
        //根据company_id获取对应的任务信息
        this.$http({
          url: this.$http.adornUrl(`/company/task/${company_id}`),
          method: 'get'
        }).then((res) => {
          if(res.data.code === 0) {
            this.tasks = res.data.result
          }
        })
        this.dataForm.task_id = ''
      },
      handleFileChange(file) {
        if (file.raw.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' && file.raw.type !== 'application/vnd.ms-excel') {
          this.$message.error('文件类型错误！')
          return false
        }
        if(file.size > 3 * 1024 * 1024) {
          this.$message.error('只支持3M以内的文件上传！')
          return false
        }
        this.dataForm.file_name = file.name
      },
      handleUploadSuccess(res) {
        console.log(res)
        if(res.code === 0) {
          this.type = 'validate'
          this.headData = res.data.header
          this.tableData = res.data.list
        } else {
          this.$message.error(res.msg)
        }
        this.dataForm.fileList = []
        this.$nextTick(() => {
          this.dataForm.file_name = ''
        })
      },
      handleUploadError() {
        this.dataForm.fileList = []
        this.$nextTick(() => {
          this.dataForm.file_name = ''
        })
      },
      getUrl(type) {
        return this.$http.adornUrl(`/payment/parser`)
      },
      dataFormSubmit() {
        if(!this.dataForm.file_name) {
          this.$message.error("请选择文件")
          return
        }
        if(!this.dataForm.company_id) {
          this.$message.error("请选择企业")
          return
        }
        if(!this.dataForm.date) {
          this.$message.error("请选择周期")
          return
        }
        if(!this.dataForm.company_id) {
          this.$message.error("请输入支付金额")
          return
        }
        if(!this.dataForm.task_id) {
          this.$message.error("请选择所属任务")
          return
        }
        this.$refs.upload.submit()
      }
    }
  }
</script>


<style lang="scss" scoped>
  .box-card {
    margin-bottom: 20px;
  }
  .desc {
    .danger-text {
      color: #f56c6c;
    }
  }
</style>
